<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="检验编号" prop="inspectionCode">
        <el-input
          v-model="queryParams.inspectionCode"
          placeholder="请输入检验编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="关联工单ID" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入关联工单ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择产品"
          clearable
          @keyup.enter="handleQuery"
        >
        <el-option
          v-for="item in productOptions"
          :key="item.productId"
          :label="item.productName"
          :value="item.productId"
        />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="检验员ID" prop="inspectorId">
        <el-input
          v-model="queryParams.inspectorId"
          placeholder="请输入检验员ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="检验员" prop="inspectorId">
        <el-select
          v-model="queryParams.inspectorId"
          placeholder="请选择检验员"
          clearable
          @keyup.enter="handleQuery"
        >
        <el-option
          v-for="item in inspectiorOptions"
          :key="item.inspectorId"
          :label="item.inspectorName"
          :value="item.inspectorId"
        />
        </el-select>
      </el-form-item> -->
      <el-form-item label="检验时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeInspectionTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="抽样数量" prop="sampleQuantity">
        <el-input
          v-model="queryParams.sampleQuantity"
          placeholder="请输入抽样数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合格数量" prop="qualifiedQuantity">
        <el-input
          v-model="queryParams.qualifiedQuantity"
          placeholder="请输入合格数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="不合格数量" prop="unqualifiedQuantity">
        <el-input
          v-model="queryParams.unqualifiedQuantity"
          placeholder="请输入不合格数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验结果" prop="result">
        <el-select v-model="queryParams.result" placeholder="请选择检验结果" clearable>
          <el-option
            v-for="dict in quality_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qc:inspection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qc:inspection:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qc:inspection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['qc:inspection:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检验ID" align="center" prop="inspectionId" />
      <el-table-column label="检验编号" align="center" prop="inspectionCode" />
      <!-- <el-table-column label="关联工单ID" align="center" prop="orderId" /> -->
      <el-table-column label="关联工单" align="center" prop="orderCode" />
      <!-- <el-table-column label="产品ID" align="center" prop="productId" /> -->
      <el-table-column label="产品" align="center" prop="productName" />
      <!-- <el-table-column label="检验员ID" align="center" prop="inspectorId" /> -->
      <!-- <el-table-column label="检验员" align="center" prop="inspectorName" /> -->
      <el-table-column label="检验时间" align="center" prop="inspectionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="抽样数量" align="center" prop="sampleQuantity" />
      <el-table-column label="合格数量" align="center" prop="qualifiedQuantity" />
      <el-table-column label="不合格数量" align="center" prop="unqualifiedQuantity" />
      <el-table-column label="检验结果" align="center" prop="result">
        <template #default="scope">
          <dict-tag :options="quality_result" :value="scope.row.result"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qc:inspection:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qc:inspection:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 引入工单选择器组件 -->
    <WorkorderSelector 
      ref="workorderSelectorRef" 
      v-model:visible="workorderSelectorVisible" 
      :filters="{ status: '3' }" 
      @select="handleWorkorderSelected" 
    />

    <!-- 添加或修改质量检验对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="inspectionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="检验编号" prop="inspectionCode">
          <el-input v-model="form.inspectionCode" placeholder="请输入检验编号" disabled />
        </el-form-item>
        <el-form-item label="关联工单" prop="orderId">
          <div class="workorder-selector-container">
            <el-input 
              v-model="selectedWorkorderName" 
              placeholder="请选择关联工单" 
              readonly 
              class="workorder-input"
              disabled
            >
              <template #append>
                <el-button @click="openWorkorderSelector">选择</el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品" filterable clearable disabled>
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="检验员ID" prop="inspectorId">
          <el-input v-model="form.inspectorId" placeholder="请输入检验员ID" />
        </el-form-item> -->
        <!-- <el-form-item label="检验员" prop="inspectorId">
          <el-select v-model="form.inspectorId" placeholder="请选择检验员" filterable clearable>
            <el-option
              v-for="item in inspectiorOptions"
              :key="item.inspectorId"
              :label="item.inspectorName"
              :value="item.inspectorId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="检验时间" prop="inspectionTime">
          <el-date-picker clearable
            v-model="form.inspectionTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择检验时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="抽样数量" prop="sampleQuantity">
          <el-input-number 
            v-model="form.sampleQuantity" 
            placeholder="请输入抽样数量" 
            :min="0"
            @change="calculateUnqualifiedQuantity"
          />
        </el-form-item>
        <el-form-item label="合格数量" prop="qualifiedQuantity">
          <el-input-number 
            v-model="form.qualifiedQuantity" 
            placeholder="请输入合格数量" 
            :min="0" 
            :max="form.sampleQuantity || 0"
            @change="calculateUnqualifiedQuantity"
          />
        </el-form-item>
        <el-form-item label="不合格数量" prop="unqualifiedQuantity">
          <el-input 
            v-model="form.unqualifiedQuantity" 
            placeholder="不合格数量" 
            disabled 
          />
        </el-form-item>
        <el-form-item label="检验结果" prop="result">
          <el-select v-model="form.result" placeholder="请选择检验结果">
            <el-option
              v-for="dict in quality_result"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Inspection">
import { listInspection, getInspection, delInspection, addInspection, updateInspection,listProduct,listWorkorder,listInspector } from "@/api/qc/inspection";
import WorkorderSelector from "@/components/WorkorderSelector/index.vue";
import { ref, reactive, toRefs, computed, watch, getCurrentInstance, onMounted } from 'vue';
import { generateInspectionCode } from "@/utils/generator";
const { proxy } = getCurrentInstance();
const { quality_result, workorder_status } = proxy.useDict('quality_result', 'workorder_status');

const inspectionList = ref([]);
const productOptions = ref([]); //新增产品选项
// const inspectiorOptions = ref([]); //新增检验员选项
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeInspectionTime = ref([]);
const workorderSelectorVisible = ref(false);
const workorderSelectorRef = ref(null);
const selectedWorkorderName = ref('');

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inspectionCode: null,
    orderId: null,
    productId: null,
    inspectorId: null,
    inspectionTime: null,
    sampleQuantity: null,
    qualifiedQuantity: null,
    unqualifiedQuantity: null,
    result: null,
  },
  rules: {
    inspectionCode: [
      { required: true, message: "检验编号不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "关联工单ID不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
    // inspectorId: [
    //   { required: true, message: "检验员ID不能为空", trigger: "blur" }
    // ],
    inspectionTime: [
      { required: true, message: "检验时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询质量检验列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeInspectionTime && '' != daterangeInspectionTime) {
    queryParams.value.params["beginInspectionTime"] = daterangeInspectionTime.value[0];
    queryParams.value.params["endInspectionTime"] = daterangeInspectionTime.value[1];
  }
  listInspection(queryParams.value).then(response => {
    inspectionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 计算不合格数量
function calculateUnqualifiedQuantity() {
  // 确保是数字类型
  const sampleQty = Number(form.value.sampleQuantity || 0);
  const qualifiedQty = Number(form.value.qualifiedQuantity || 0);
  
  // 合格数量不能大于抽样数量
  if (qualifiedQty > sampleQty) {
    form.value.qualifiedQuantity = sampleQty;
  }
  
  // 计算不合格数量
  form.value.unqualifiedQuantity = Math.max(0, sampleQty - qualifiedQty);
}

// 监听抽样数量和合格数量变化
watch(() => form.value.sampleQuantity, () => {
  calculateUnqualifiedQuantity();
});

watch(() => form.value.qualifiedQuantity, () => {
  calculateUnqualifiedQuantity();
});

// 表单重置
function reset() {
  form.value = {
    inspectionId: null,
    inspectionCode: null,
    orderId: null,
    productId: null,
    inspectorId: null,
    inspectionTime: null,
    sampleQuantity: 0,
    qualifiedQuantity: 0,
    unqualifiedQuantity: 0,
    result: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  selectedWorkorderName.value = '';
  proxy.resetForm("inspectionRef");
  calculateUnqualifiedQuantity(); // 确保重置后计算正确
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeInspectionTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.inspectionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.inspectionCode = generateInspectionCode();
  open.value = true;
  title.value = "添加质量检验";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _inspectionId = row.inspectionId || ids.value
  getInspection(_inspectionId).then(response => {
    form.value = response.data;
    calculateUnqualifiedQuantity(); // 确保加载数据后计算正确
    open.value = true;
    title.value = "修改质量检验";
  });
}

/** 提交按钮 */
function submitForm() {
  // 先计算最终的不合格数量
  calculateUnqualifiedQuantity();
  
  proxy.$refs["inspectionRef"].validate(valid => {
    if (valid) {
      if (form.value.inspectionId != null) {
        updateInspection(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInspection(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _inspectionIds = row.inspectionId || ids.value;
  proxy.$modal.confirm('是否确认删除质量检验编号为"' + _inspectionIds + '"的数据项？').then(function() {
    return delInspection(_inspectionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('qc/inspection/export', {
    ...queryParams.value
  }, `inspection_${new Date().getTime()}.xlsx`)
}

// 打开工单选择器
function openWorkorderSelector() {
  workorderSelectorRef.value.open();
  workorderSelectorVisible.value = true;
}

// 处理工单选择事件
function handleWorkorderSelected(result) {
  console.log("选择的工单信息:", result);
  if (result && result.workorder) {
    const workorder = result.workorder;
    
    // 检查工单状态是否为"已完成"
    if (String(workorder.status) != '3') {
      proxy.$modal.msgError("只能选择已完成的工单进行检验");
      return;
    }
    
    form.value.orderId = workorder.orderId;
    selectedWorkorderName.value = workorder.orderCode;
    
    // 自动填充产品信息
    if (workorder.productId) {
      form.value.productId = workorder.productId;
      // 查找产品名称
      const product = productOptions.value.find(p => p.productId === workorder.productId);
      if (product) {
        form.value.productName = product.productName;
      }
    }
    
    console.log("设置后的表单数据:", form.value);
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  // 获取产品列表
  listProduct().then(response => {
    productOptions.value = response.data; // 根据接口返回结构调整
  });
  //获取检验员列表
  // listInspector().then(response => {
  //   inspectiorOptions.value = response.data; // 根据接口返回结构调整 
  // })
  getList(); // 原有的获取计划列表
});
</script>

<style scoped>
.workorder-selector-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.workorder-input {
  width: 100%;
  max-width: 300px;
}
.workorder-tag {
  margin-top: 5px;
  margin-left: 5px;
}
</style>
